import React from "react";
import { createRoot } from "react-dom/client";
import type { UIController } from "../App";
import IconButton from "@mui/material/IconButton";
import AddIcon from "@mui/icons-material/Add";

let controllerRef: UIController | null = null;

export function bindController(controller: UIController) {
  controllerRef = controller;
}

/** 注入加号按钮 */
export function injectPlusButtons(root: ParentNode) {
  const candidates = root.querySelectorAll('a[href*="/explore/"], div[data-note-id]');
  candidates.forEach((el) => {
    const card = el as HTMLElement;
    if (!card || card.dataset.wxtPlusAttached === "1") return;
    const mount = document.createElement("div");
    mount.className = "wxt-plus-btn-mount";
    mount.style.position = "absolute";
    mount.style.top = "8px";
    mount.style.right = "8px";
    mount.style.zIndex = "1000";
    if (!card.style.position || card.style.position === "") {
      card.style.position = "relative";
    }
    card.appendChild(mount);
    const root = createRoot(mount);
    root.render(<PlusButton onClick={() => onPlusClicked(card as HTMLAnchorElement)} />);
    card.dataset.wxtPlusAttached = "1";
  });
}

/** 帖子信息 */
interface PostInfo {
  /** 标题 */
  title: string | null;
  /** 描述 */
  desc: string;
  /** 标签列表 */
  tagList: string[];
  /** 链接 */
  url: string;
}
/** 加号按钮点击事件 */
export async function onPlusClicked(card: HTMLAnchorElement): Promise<PostInfo> {
  const url = card.href;
  const fullUrl = new URL(url, window.location.origin).toString();
  const res = await fetch(fullUrl);
  const html = await res.text();
  const dom = new DOMParser().parseFromString(html, "text/html");
  const title = dom.querySelector("#detail-title");
  const content = dom.querySelector("#detail-desc .note-text");
  const tagList: string[] = [];
  let desc = "";
  if (content) {
    Array.from(content.children).forEach((child: Element) => {
      const text = child.textContent?.trim();
      if (!text) return;
      if (text.startsWith("#")) {
        return tagList.push(text.slice(1).trim());
      }
      desc += text;
    });
  }
  controllerRef?.showToast("已添加此帖子", "success");
  return {
    title: title?.textContent?.trim() || null,
    desc,
    tagList,
    url: fullUrl,
  };
}
/** 加号按钮 */
function PlusButton(props: { onClick: () => void }) {
  return (
    <IconButton
      size="small"
      onClick={(e) => {
        e.stopPropagation();
        e.preventDefault();
        props.onClick();
      }}
      sx={{
        width: 28,
        height: 28,
        borderRadius: "50%",
        backgroundColor: "#4caf50",
        color: "#fff",
        boxShadow: "0 2px 6px rgba(0,0,0,0.2)",
        "&:hover": { backgroundColor: "#43a047" },
      }}>
      <AddIcon fontSize="small" />
    </IconButton>
  );
}
